package com.szosen.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import net.vidageek.mirror.dsl.Mirror;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.itextpdf.text.pdf.PdfStructTreeController.returnType;
import com.szosen.util.NetWork.NetType;

public class Tools {
	public static byte[] shortToBytes(short n) {
		byte[] b = new byte[2];
		b[0] = (byte) (n & 0xFF);
		b[1] = (byte) ((n >> 8) & 0xFF);
		return b;
	}

	@SuppressLint("NewApi")
	public static String getSerialNumber() {
		return android.os.Build.SERIAL;
	}

	public static String getBTAddress(Context context) {
		final BluetoothManager bluetoothManager = (BluetoothManager) context
				.getSystemService(Context.BLUETOOTH_SERVICE);
		if (bluetoothManager != null) {
			BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
			if (!mBluetoothAdapter.isEnabled()) {
				mBluetoothAdapter.enable();
			}
		}
		String result = getBtAddressViaReflection();
		if (result == null) {
			return "";
		}
		return result;
	}

	/***
	 * 保存秘钥到sd卡中
	 * 
	 * @param fileContent
	 * @return
	 */
	public static boolean saveMiYao2SD(String fileContent) {
		File mainFile = null;
		// 获得sd卡根目录
		boolean result = false;
		mainFile = new File(FileSaveUtil.getSDCardPath(), "miyao.bin");
		try {
			if (!mainFile.exists()) {
				mainFile.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(mainFile);
			// System.out.println("fileSaveUtil。savetxtfile内容"+fileContent);
			fos.write(fileContent.getBytes());
			fos.flush();
			fos.close();
			result = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/***
	 * 读取秘钥
	 * 
	 * @return
	 */
	public static String readMiyaoContent() {
		StringBuilder result = new StringBuilder();
		try {
			File mainFile = new File(FileSaveUtil.getSDCardPath(), "miyao.bin");
			if (!mainFile.exists()) {
				return "";
			}
			BufferedReader br = new BufferedReader(new FileReader(mainFile));// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				result.append(s);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return result.toString().trim();
	}

	private static String getBtAddressViaReflection() {
		BluetoothAdapter bluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();
		Object bluetoothManagerService = new Mirror().on(bluetoothAdapter)
				.get().field("mService");
		if (bluetoothManagerService == null) {
			// Log.w(TAG, "couldn't find bluetoothManagerService");
			return null;
		}
		Object address = new Mirror().on(bluetoothManagerService).invoke()
				.method("getAddress").withoutArgs();
		if (address != null && address instanceof String) {
			// Log.w(TAG, "using reflection to get the BT MAC address: " +
			// address);
			return ((String) address).replace(":", "").replace("：", "");
		} else {
			return null;
		}
	}

	public static String getWlanMacAddress() {
		Enumeration<NetworkInterface> interfaces;
		String result = "";
		try {
			// NetworkInterface iF2 =NetworkInterface.getByName("wlan0");
			// byte[] addr2 = iF2.getHardwareAddress();
			// StringBuilder buf2 = new StringBuilder();
			// for (byte b : addr2) {
			// buf2.append(String.format("%02X", b));
			// }
			// System.out.println("健康专家wlan0interfaceName=" + iF2.getName() +
			// ", mac=" + buf2.toString());
			interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface iF = interfaces.nextElement();
				byte[] addr = iF.getHardwareAddress();
				if (addr == null || addr.length == 0) {
					continue;
				}
				StringBuilder buf = new StringBuilder();
				for (byte b : addr) {
					buf.append(String.format("%02X", b));
				}
				// if (buf.length() > 0) {
				// buf.deleteCharAt(buf.length() - 1);
				// }
				String mac = buf.toString();
				System.out.println("健康专家interfaceName=" + iF.getName()
						+ ", mac=" + mac);
			}
		} catch (SocketException e) {
			e.printStackTrace();
			return "";
		}
		return result;
	}

	public static String getSerialNumber2() {
		String serial = null;
		try {
			Class<?> c = Class.forName("android.os.SystemProperties");
			Method get = c.getMethod("get", String.class);
			serial = (String) get.invoke(c, "ro.serialno");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return serial;
	}

	public static short bytesToShort(byte[] b, int offset) {
		return (short) ((((b[offset + 1] + 0x100) % 0x100) << 8) + ((b[offset] + 0x100) % 0x100));
	}

	/***
	 * 通过idCard身份证号码获取多少岁
	 * 
	 * @param idCard
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static int getYearoldByIdcard(String idCard) {
		if (TextUtils.isEmpty(idCard)) {
			return 0;
		} else {
			int age = 0;
			if (idCard.length() == 18) {
				String year = idCard.substring(6, 10);
				String month = idCard.substring(10, 12);
				Date now = new Date();
				SimpleDateFormat format_y = new SimpleDateFormat("yyyy");
				SimpleDateFormat format_M = new SimpleDateFormat("MM");
				String this_year = format_y.format(now);
				String this_month = format_M.format(now);
				// 初步，估算
				age = Integer.parseInt(this_year) - Integer.parseInt(year);
				// 如果未到出生月份，则age - 1
				if (this_month.compareTo(month) < 0)
					age -= 1;
				if (age < 0)
					age = 0;
			}
			return age;
		}
	}
	/***
	 * 通过idCard身份证号码获取多少岁
	 * 
	 * @param idCard
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getBirthdayByIdcard(String idCard) {
		if (TextUtils.isEmpty(idCard)) {
			return "";
		} else {
			int age = 0;
			if (idCard.length() == 18) {
				String year = idCard.substring(6, 10);
				String month = idCard.substring(10, 12);
				String day = idCard.substring(12, 14);
				return year+"-"+month+"-"+day;
			}
			return "";
		}
	}

	public static int getAge(Date birthDate) {
		if (birthDate == null)
			throw new RuntimeException("出生日期不能为null");
		int age = 0;
		Date now = new Date();
		SimpleDateFormat format_y = new SimpleDateFormat("yyyy");
		SimpleDateFormat format_M = new SimpleDateFormat("MM");
		String birth_year = format_y.format(birthDate);
		String this_year = format_y.format(now);
		String birth_month = format_M.format(birthDate);
		String this_month = format_M.format(now);
		// 初步，估算
		age = Integer.parseInt(this_year) - Integer.parseInt(birth_year);
		// 如果未到出生月份，则age - 1
		if (this_month.compareTo(birth_month) < 0)
			age -= 1;
		if (age < 0)
			age = 0;
		return age;
	}

	/***
	 * 将汉字转换成byte 数组
	 * 
	 * @param data
	 *            待转换数组
	 * @param count
	 *            转换的长度
	 * @return
	 */
	public static byte[] stringToBytes(String data, int count) {
		byte[] tempdata = new byte[count];
		byte[] temp;
		try {
			temp = data.getBytes("GBK");
			System.arraycopy(temp, 0, tempdata, 0, temp.length);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tempdata;
	}

	public static void stringToBytes(String data, byte[] buffer, int offset,
			int count) {
		try {
			byte[] temp = data.getBytes("GBK");
			System.arraycopy(temp, 0, buffer, offset,
					Math.min(temp.length, count));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/***
	 * 将字符数组转换成字符串
	 * 
	 * @param data
	 *            待转换数组
	 * @return 转换之后的字符串
	 */
	public static String bytesToString(byte[] data, int offset, int size) {
		String temp = "";
		int count = 0;
		for (int i = 0; i < size; i++) {
			if (data[i + offset] != 0x00) {
				count++;
			} else {
				break;
			}
		}
		if (count == 0) {
			return temp;
		}
		byte[] tempdata = new byte[count];
		System.arraycopy(data, offset, tempdata, 0, count);
		try {
			temp = new String(tempdata, "GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
		return temp;
	}

	/***
	 * 将获取的字节长度转换成INT
	 * 
	 * @param b0
	 *            低1字节
	 * @param b1
	 *            低2字节
	 * @param b2高1字节
	 * @param b3高2字节
	 */
	public static int bytesToInt(byte[] buffer, int offset) {
		int length = 0;
		length = (buffer[offset + 3] + 0x100) % 0x100;
		length = length << 8;
		length += (buffer[offset + 2] + 0x100) % 0x100;
		length = length << 8;
		length += (buffer[offset + 1] + 0x100) % 0x100;
		length = length << 8;
		length += (buffer[offset] + 0x100) % 0x100;
		return length;
	}

	/***
	 * 4字节 int 转换成byte[];
	 * 
	 * @param data
	 * @return
	 */
	public static byte[] intToBytes(int data) {
		byte[] tempbyte = new byte[4];
		tempbyte[0] = (byte) (data & 0x000000FF);
		tempbyte[1] = (byte) ((data >> 8) & 0x000000FF);
		tempbyte[2] = (byte) ((data >> 16) & 0x000000FF);
		tempbyte[3] = (byte) ((data >> 24) & 0x000000FF);
		return tempbyte;
	}

	public static byte[] intToBytes(int data, byte[] buffer, int offset) {
		byte[] tempbyte = buffer;
		tempbyte[offset] = (byte) (data & 0x000000FF);
		tempbyte[offset + 1] = (byte) ((data >> 8) & 0x000000FF);
		tempbyte[offset + 2] = (byte) ((data >> 16) & 0x000000FF);
		tempbyte[offset + 3] = (byte) ((data >> 24) & 0x000000FF);
		return tempbyte;
	}

	public static byte[] floatToBytes(float data) {
		return intToBytes(Float.floatToIntBits(data));
	}

	/***
	 * 检查网络连接状态
	 * 
	 * @return
	 */
	public static NetType cheackNetConnection(Context context) {
		ConnectivityManager ConManager = null;
		try {
			ConManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			// 获取WIFI网络连接状态
			NetworkInfo.State wifi_state = ConManager.getNetworkInfo(
					ConnectivityManager.TYPE_WIFI).getState(); //
			NetworkInfo mNetworkInfo = ConManager.getActiveNetworkInfo();
			if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
				if (mNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET)
					return NetType.Net_ETHERNET;
			}
			if (wifi_state == NetworkInfo.State.CONNECTED) {
				return NetType.NET_WIFI;
			} else {
				// 判断3G网络连接状态
				NetworkInfo.State mobile_state = null;
				try {
					mobile_state = ConManager.getNetworkInfo(
							ConnectivityManager.TYPE_MOBILE).getState();
				} catch (Exception e) {
					e.printStackTrace();
					return NetType.NET_NONE;
				}
				if (mobile_state == NetworkInfo.State.CONNECTED) {
					return NetType.NET_3G;
				} else {
					return NetType.NET_NONE;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return NetType.NET_NONE;
		}
	}

	/*****
	 * 获取当前时间
	 */
	public static String GetCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(new Date());
	}

	public static String GetCurrentTime(String format) {
		SimpleDateFormat sdformat = new SimpleDateFormat(format);
		return sdformat.format(new Date());
	}

	public static boolean isNetConnected(Context context) {
		NetType type = cheackNetConnection(context);
		switch (type) {
		case Net_ETHERNET:
			// ToastTool.showLong(context, "当前网络为以太网网络!");
			return true;
		case NET_3G:
			// ToastTool.showLong(context, "当前网络为移动网络，可能会产生流量费用!");
		case NET_WIFI:
			return true;
		case NET_NONE:
		default:
			// ToastTool.showLong(context, "当前网络不可用!");
			return false;
		}
	}

	public static String getVersionCode(final Context context) {
		final String packageName = context.getPackageName();
		String version = "1";
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					packageName, 0);
			version = info.versionName;
		} catch (NameNotFoundException e) {
		}
		return version;
	}
}
